#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MULTICAST_ADDR "224.1.1.2"  
#define PORT 12345                  
#define MAX_MSG_LEN 1024            

int main() {
    int sockfd;
    struct sockaddr_in addr;
    char message[MAX_MSG_LEN];

  
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket");
        exit(1);
    }

    struct ip_mreq mreq;
    mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_ADDR);
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
        perror("setsockopt");
        exit(1);
    }

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind");
        exit(1);
    }

    printf("Server started, waiting for messages...\n");

    while (1) {
        memset(message, 0, sizeof(message));
        if (recvfrom(sockfd, message, sizeof(message), 0, NULL, NULL) < 0) {
            perror("recvfrom");
            exit(1);
        }

        printf("Received: %s\n", message);
    }

    close(sockfd);

    return 0;
}

